package com.example.shirospringboottest.controller;

import com.example.shirospringboottest.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {

    @GetMapping("/loginController")
    public String userLogin(User user, String rememberMe, Model model, HttpServletRequest req) {

        System.out.println("LoginController.userLogin 认证异常才进入");

        Object exception = req.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);

        System.out.println("exception = " + exception);

        /**
         * 灵感来源
         * https://segmentfault.com/a/1190000019440231
         */
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
        /**
         * input name="rememberMe" 不可以有value=""
         */
        token.setRememberMe("on".equals(rememberMe));

        try {
            subject.login(token);
        }catch (UnknownAccountException u){
            u.printStackTrace();
            System.err.println("用户名不存在");
            model.addAttribute("msg","用户名不存在");
            return "redirect:/loginPage";
        }

        if(subject.isAuthenticated()){
            return "redirect:/index-x";
        }else{
            return "redirect:/loginPage";
        }

        /*if (exception instanceof IncorrectCredentialsException) {
            req.setAttribute("message", "用户凭证不正确");
        } else if (exception instanceof ExcessiveAttemptsException) {
            req.setAttribute("message", "尝试次数过多");
        } else if (exception instanceof UnknownAccountException) {
            req.setAttribute("message", "未知的账户异常");
        }*/



    }
}
